﻿$(function () {
    var cardViewThreshold = 580;
    /* Set a locale manually */
    //$.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['en-US']);
    loaddata();
    /* Auto adjust the table's view type (table/card) when screen size changes */
    //window.onresize = function () {
    //    $('#table').bootstrapTable('refreshOptions', {
    //        cardView: document.body.clientWidth < cardViewThreshold
    //    });
    //};
});
function reloaddata() {
    //var opt = {
    //    url: "/lxoa/listvacation/"
    //};
    //$('#table').bootstrapTable('refresh', opt);

    $.ajax({
        url: '/lxoa/listvacation/',
        type: 'get',
        dataType: 'json',
        headers: { "X-CSRFToken": getCookie('csrftoken') },
        success: function (data) {
            if (data && data.total > 0) {
                $("#table").bootstrapTable('load', data.rows);
            } else {
                //alert('error');
            }
        }
    })  
}

function loaddata() {
    $.ajax({
        url: '/lxoa/listvacation/',
        type: 'get',
        dataType: 'json',
        headers: { "X-CSRFToken": getCookie('csrftoken') },        
        success: function (data) {
            if (data && data.total>0) {
                binddata(data.rows);
                $('.columns-right').append('<button class="btn btn-primary" type="button" data-toggle="modal" data-target="#myModal" name="toggle" aria-label="toggle" title=""> 申请 </button>&nbsp;<button class="btn btn-primary" style="margin-left:4px;" type="button" onclick="vacationtj()" name="toggle" aria-label="toggle" title=""> 统计 </button>');
                $('.keep-open').hide();
                var uname = $('#usernamespan').html();
                $("#vac_person").empty().append("<option value='" + uname + "' mail=''>" + uname + "</option>").attr("disabled", "disabled");
                //getuserlist();//order last one load it.

                //alert('success');
            } else {
                //alert('error');
            }
        }
    })
}

function binddata(datas) {
    var cardViewThreshold = 580;
    $('#table').bootstrapTable({
        cardView: document.body.clientWidth < cardViewThreshold,
        //striped: true,
        search: true,
        pagination: true,
        ageNumber: 1,
        pageSize: 10,
        pageList: [10, 20, 30, 50],
        showColumns: true,
        showToggle: false,
        //showExport: false,
        columns: [{
            title: '序号',
            field: '',
            formatter: function (value, row, index) {
                return index + 1;
            }
        },{
            field: 'vac_person',
            title: '请假人',
            sortable: true
        }, 
        {
            field: 'vac_type',
            title: '请假类型',
            sortable: true
            },
        {
            field: 'vac_interval',
            title: '请假时长(天)',
            sortable: true
        },
        {
            field: 'vac_date',
            title: '开始时间',
            sortable: true
        },
        {
            field: 'vac_enddate',
            title: '结束时间',
            sortable: true
        },
        {
            field: 'vac_temp',
            title: '办公地点',
            sortable: true
        },
        {
            field: 'vac_reason',
            title: '请假原因',
            sortable: true
        }],
        data: datas
    });
}

function getuserlist() {
    $.ajax({
        url: '/lxoa/getuserlist/',
        type: 'get',
        dataType: 'json',
        headers: { "X-CSRFToken": getCookie('csrftoken') },
        success: function (data) {
            if (data && data.length > 0) {
                $("#vac_person").empty();
                $("#vac_person2").empty();
                for (var i = 0; i < data.length; i++) {
                    $("#vac_person").append("<option value='" + data[i].USER + "' mail='" + data[i].MAIL + "'>" + data[i].USER + "</option>");
                    $("#vac_person2").append("<option value='" + data[i].USER + "' mail='" + data[i].MAIL + "'>" + data[i].USER + "</option>");
                }
                //alert('success');
            } else {
                //alert('error');
            }
        }
    })
}

var gyear = $('#vac_year');
var y = new Date().getFullYear();
gyear.empty();
gyear.append("<option value=''>All</option>");
for (var i = 0; i < 5; i++) {
    var c = (y + i) == y ? "selected='selected'" : "";
    gyear.append("<option " + c + " value='" + (y + i) + "'>" + (y + i) + "年</option>");
}

Date.prototype.addDays = function (day, number) {
    var adjustDate = new Date(day + 24 * 60 * 60 * 1000 * 30 * number)
    //alert("Date" + adjustDate.getFullYear() + "-" + adjustDate.getMonth() + "-" + adjustDate.getDate());
    return adjustDate;
}
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds() //??
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

Date.prototype.addDays2 = function (d) {
    this.setDate(this.getDate() + d);
    return this.Format('yyyy-MM-dd');
};
laydate.render({
    elem: '#vac_date',
    lang: 'zh',
    done: function (value, date, endDate) {
        if (value && value.length > 0) {
            $('#vac_date').attr('style', 'border:1px solid #ccc;');
            var curDate = new Date(value);
            $('#vac_enddate').val(curDate.addDays2(parseFloat($('#vac_interval').val())));
        } else {
            $('#vac_enddate').val('');
        }
    }
});

$("#submitbtn").click(function () {
    //if ($('#vac_person').val().length < 1 || $('#vac_person').val() != $('#vac_person2').val()) {
    //    $('#vac_person2').attr('style', 'border:1px solid red;');
    //    return;
    //}
    var vac_dateobj = $('#vac_date');
    if (vac_dateobj && vac_dateobj.val().length > 0) {
        $.ajax({
            url: '/lxoa/savevacation/',
            type: 'POST',
            dataType: 'json',
            headers: { "X-CSRFToken": getCookie('csrftoken') },
            data: {
                vac_date: $('#vac_date').val(),
                vac_person: $('#vac_person').val(),
                vac_interval: $('#vac_interval').val(),
                vac_type: $('#vac_type').val(),
                vac_reason: $('#vac_reason').val(),
                vac_enddate: $('#vac_enddate').val(),
                vac_office: $('#vac_office').val()
            },
            success: function (data) {
                if (data && data.success == '1') {

                    $('#myAlert').removeClass('hidden');
                    setTimeout(function () {
                        $('#myModal').modal('hide');
                        $('#myAlert').addClass('hidden');
                        reloaddata();
                        sendmail();
                        //$('#table').bootstrapTable('refresh');
                        //loaddata();
                    }, 1000);

                } else {
                    $('#myAlerterror').removeClass('hidden');
                    setTimeout(function () {
                        $('#myAlerterror').addClass('hidden');
                    }, 1500);
                }
            }
        })

    } else {
        vac_dateobj.attr('style', 'border:1px solid red;');
    }
})
function sendmail() {
    var vac_date = $('#vac_date').val();
    var vac_person = $('#vac_person').val();
    var vac_interval = $('#vac_interval').val();
    var vac_type = $('#vac_type').val();
    var vac_reason = $('#vac_reason').val();
    var vac_enddate = $('#vac_enddate').val();
    var vac_office = $('#vac_office').val();
    var contents1 = vac_person + ' 请假 ' + vac_interval + " 天,开始时间 " + vac_date + "日 结束时间 " + vac_enddate + "日 ,请假类型 " + vac_type + " office " + vac_office + " 请假原因 " + vac_reason + "。";
    var contents = "<h3>" + vac_person + "请假信息如下：</h3><br/><table border='0' style=''><tr> <td> " + vac_person + " </td><td> 请假" + vac_interval + "天</td></tr><tr><td> 开始时间</td><td> " + vac_date + "日</td></tr><tr><td>结束时间</td><td> " + vac_enddate + "日</td></tr><tr><td>请假类型</td><td> " + vac_type + "</td></tr><tr><td>办公地址</td><td> " + vac_office + "</td></tr><tr><td>请假原因</td><td> " + vac_reason + "</td></tr></table>";
    $.ajax({
        url: '/lxoa/sendmail/',
        type: 'POST',
        dataType: 'json',
        headers: { "X-CSRFToken": getCookie('csrftoken') },
        data: { contenttitle: contents1, content: contents },
        success: function (data) {
            if (data && data.success == '1') {
                //send email success clear text
                $('#vac_date').val('');
                $('#vac_reason').val('');

            } else {
            }
        }
    })
}

var myChart;
function vacationtj() {
    $('#myModaltj').modal('show');
    setTimeout(function () {
        sumyear(document.getElementById('vac_year'));
    }, 500)
}

function sumyear(obj) {
    var yearval = $(obj);

    $.ajax({
        url: '/lxoa/vacationsumyear/',
        type: 'POST',
        dataType: 'json',
        headers: { "X-CSRFToken": getCookie('csrftoken') },
        data: {
            year: yearval.val()
        },
        success: function (data) {
            //if (data && data.length > 0) {
            var person = [];
            var sum = [];
            for (var i = 0; i < data.length; i++) {
                person.push(data[i].vac_person);
                sum.push(data[i].tj);
            }

            initechar(person, sum);
            //} else {
            //    $('#divchart').html('加载失败，或暂无数据！');
            //}
        }
    })
}
function initechar(person, sum) {
    //if (person && sum && person.length > 0 && sum.length > 0) {
    if (myChart && myChart != null) {
        myChart.clear();
    } else {
        myChart = echarts.init(document.getElementById('divchart'));
    }
    myChart = echarts.init(document.getElementById('divchart'));

    var option = {
        title: {
            //text: '西安力啸科技员工请假统计'
        },
        tooltip: {},
        legend: {
            //data: ['请假天数']
        },
        //toolbox: {
        //    show: true,
        //    feature: {
        //        mark: { show: true },
        //        dataView: { show: true, readOnly: false },
        //        magicType: { show: true, type: ['line', 'bar'] },
        //        restore: { show: true },
        //        saveAsImage: { show: true }
        //    }
        //},
        //calculable: true,
        xAxis: {
            data: person,
            axisLabel: {
                interval: 0,
                rotate: 40
            }
        },
        yAxis: {},
        series: [{
            itemStyle: {
                // 点的颜色。
                color: '#428bca'
            },
            label: {
                show: true,
            },
            //name: '请假天数',
            type: 'bar',
            data: sum,
            //markPoint: {
            //    data: [
            //        { type: 'max', name: '最大值' },
            //        { type: 'min', name: '最小值' }
            //    ]
            //}
        }]
    };
    myChart.setOption(option, true);
}